const app = getApp();
var baseUrl = app.globalData.baseUrl

var getOssToken = function () {
  // const {
  //   baseUrl
  // } = this.globalData
  const nowTime = (Date.now() + '').substring(0, 11);
  const numNOWtime = Number(nowTime) + (1000 * 60 * 2)
  const numExpire = Number(app.globalData.ossToken.expire)
  console.log('nowTime', nowTime);
  if (!numExpire || numNOWtime > numExpire) {
    wx.request({
      url: baseUrl + '/oss/getToken',
      success: (res => {
        console.log("oss", res);
        const ossToken = JSON.parse(res.data.token)
        app.globalData.ossToken = ossToken
      })
    })
  }
  return _getOSS();
}

const _getOSS = function () {
  if (!app.globalData.ossToken || !app.globalData.ossToken.expire) {
    _sleep(100)
    return _getOSS();
  } else {
    return app.globalData.ossToken;
  }
}
// “休眠”函数
function _sleep(delay) {
  var start = (new Date()).getTime();
  while ((new Date()).getTime() - start < delay) {
    continue;
  }
}
// 对象转 page=1&limit=10
const setQueryConfig = function (item) {
  let _str = ''
  for (const o in item) {
    if (item[o] !== -1) {
      _str += o + '=' + item[o] + '&'
    }
  }
  _str = _str.substring(0, _str.length - 1) // 末尾是&
  return _str
}
// 数组去重函数
const arrDeduplication = function (arr) {
  var arr2 = arr.sort();
  for (var i = 1; i < arr2.length;) {
    if (arr2[i] === arr2[i - 1]) {
      arr2.splice(i, 1);
    } else {
      i++;
    }
  }
  return arr2;
}

module.exports = {
  getOssToken: getOssToken,
  setQueryConfig,
  arrDeduplication
}